<template>
  <transition name="showHeader">
    <a-layout-header
      :class="[fixedHeader && 'ant-header-fixedHeader', sidebarOpened ? 'ant-header-side-opened' : 'ant-header-side-closed', ]"
      :style="{ padding: '0' }">
      <div class="header">
        <user-menu></user-menu>
      </div>
    </a-layout-header>
  </transition>
</template>

<script>
import UserMenu from '../tools/UserMenu'
import SMenu from '../Menu/'
import { mixin } from '@/utils/mixin'
import { mapActions, mapGetters } from 'vuex'
import Vue from 'vue'
import { message } from 'ant-design-vue/es'
import { ALL_APPS_MENU } from '@/store/mutation-types'
export default {
  name: 'GlobalHeader',
  components: {
    UserMenu,
    SMenu
  },
  mixins: [mixin],
  props: {
    theme: {
      type: String,
      required: false,
      default: 'dark'
    }
  },
  data () {
    return {
      visible: true,
      device: '',
      collapsed: '',
      oldScrollTop: 0,
      defApp: []
    }
  },
  computed: {
    ...mapGetters(['userapps'])
  },
  created () {
    this.defApp.push(Vue.ls.get(ALL_APPS_MENU)[0].code)
  },
  mounted () {
    document.body.addEventListener('scroll', this.handleScroll, { passive: true })
  },
  methods: {
    ...mapActions(['MenuChange']),

    /**
     * 应用切换
     */
    switchApp (appCode) {
      this.defApp = []
      const applicationData = this.userapps.filter(item => item.code === appCode)
      const hideMessage = message.loading('正在切换应用！', 0)
      this.MenuChange(applicationData[0]).then((res) => {
        hideMessage()
        // eslint-disable-next-line handle-callback-err
      }).catch((err) => {
        message.error('应用切换异常')
      })
    },
    handleScroll () {
      if (!this.autoHideHeader) {
        return
      }

      const scrollTop = document.body.scrollTop + document.documentElement.scrollTop
      if (!this.ticking) {
        this.ticking = true
        requestAnimationFrame(() => {
          if (this.oldScrollTop > scrollTop) {
            this.visible = true
          } else if (scrollTop > 300 && this.visible) {
            this.visible = false
          } else if (scrollTop < 300 && !this.visible) {
            this.visible = true
          }
          this.oldScrollTop = scrollTop
          this.ticking = false
        })
      }
    },
    toggle () {
      this.$emit('toggle')
    }
  },
  beforeDestroy () {
    document.body.removeEventListener('scrool', this.handScroll)
  }
}
</script>

<style lang="less" scoped>
.header-animat{
  position: relative;
  z-index: 999;
}
.showHeader-enter-active {
  transition: all 0.25s ease;
}
.showHeader-leave-active {
  transition: all 0.5s ease;
}
.showHeader-enter, .showHeader-leave-to {
  opacity: 0;
}
</style>
